package com.zsix.framework.interceptor;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.util.Properties;

@Service
@Intercepts({ @Signature(type = StatementHandler.class, method = "prepare", args = { Connection.class, Integer.class }) })
/**
 * sql执行拦截器，备用
 */
public class SqlInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //获取目标
        StatementHandler statementHandler=(StatementHandler) invocation.getTarget();
        MetaObject metaObject=MetaObject.forObject(statementHandler, SystemMetaObject.DEFAULT_OBJECT_FACTORY,SystemMetaObject.DEFAULT_OBJECT_WRAPPER_FACTORY,new DefaultReflectorFactory());
        //拦截执行目标
        MappedStatement mappedStatement=(MappedStatement) metaObject.getValue("delegate.mappedStatement");
        //执行的mapper的路径
        String id=mappedStatement.getId();
        //执行sql的类型
        String sqlCommandType= mappedStatement.getSqlCommandType().toString();
        //获取sql
        BoundSql boundSql=statementHandler.getBoundSql();
        String sql= boundSql.getSql();
        //获取参数
        Object parameter=statementHandler.getParameterHandler().getParameterObject();

        //如果想处理sql语句，在这里定义业务处理
        //  调用SqlUtil进行处理
        ///
        //将处理过后的sql放入boundSql
        Field field=boundSql.getClass().getDeclaredField("sql");
        field.setAccessible(true);
        field.set(boundSql,sql);
        return invocation.proceed();
    }
    @Override
    public Object plugin(Object o) {
        return Plugin.wrap(o, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
